import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import type { 
  ConfigGroup,
  CreateConfigGroup,
  UpdateConfigGroup
} from '@/types/api/config/configGroup'
import type {
  Config,
  ConfigQuery,
  CreateConfig,
  UpdateConfig
} from '@/types/api/config/config'
import * as settingApi from '@/api/config/setting'

export const useSettingStore = defineStore('setting', () => {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 加载状态 ------------
  const loading = ref(false)
  const submitLoading = ref(false)
  
  // ------------ 数据列表 ------------
  const groupList = ref<ConfigGroup[]>([])
  const configList = ref<Config[]>([])
  
  // ------------ 查询参数 ------------
  const queryParams = reactive<ConfigQuery>({
    configName: '',
    configKey: '',
    groupId: undefined,
    page: 1,
    pageSize: 10
  })
  
  // ------------ 弹窗状态 ------------
  const groupModalVisible = ref(false)
  const configModalVisible = ref(false)
  
  // ------------ 表单状态 ------------
  const groupFormMode = ref<'add' | 'edit'>('add')
  const configFormMode = ref<'add' | 'edit'>('add')
  const currentGroupId = ref<string>('')
  
  const groupFormData = reactive<CreateConfigGroup & { id?: string }>({
    name: '',
    code: '',
    icon: 'setting',
    sort: 0,
    remark: ''
  })
  
  // 使用CreateConfig类型并添加可选的id字段
  const configFormData = reactive<CreateConfig & { id?: string }>({
    groupId: '',
    configName: '',
    configKey: '',
    configValue: '',
    valueType: 'string',
    builtIn: false,
    remark: ''
  })
  
  // ------------ 分页配置 ------------
  const pagination = reactive<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true
  })
  
  // ------------ 计算属性 ------------
  const groupModalTitle = computed(() => groupFormMode.value === 'add' ? t('setting.addGroup') : t('setting.editGroup'))
  const configModalTitle = computed(() => configFormMode.value === 'add' ? t('setting.addConfig') : t('setting.editConfig'))
  const currentGroupName = computed(() => {
    const group = groupList.value.find(g => g.id === currentGroupId.value)
    return group?.name || ''
  })
  
  // ------------ 数据操作方法 ------------
  /**
   * 获取配置分组列表
   */
  const fetchGroupList = async () => {
    try {
      const result = await settingApi.getConfigGroups()
      if (result.success) {
        groupList.value = result.data
      } else {
        message.error(result.message || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
      groupList.value = []
    }
  }
  
  /**
   * 获取配置列表
   */
  const fetchConfigList = async () => {
    if (!currentGroupId.value) return
    
    loading.value = true
    try {
      const result = await settingApi.getConfigList({
        ...queryParams,
        groupId: currentGroupId.value
      })
      if (result.success) {
        // 处理响应数据，兼容两种可能的格式
        if (Array.isArray(result.data)) {
          configList.value = result.data
          pagination.total = result.data.length
        } else if (result.data && typeof result.data === 'object' && 'list' in result.data) {
          configList.value = result.data.list
          pagination.total = result.data.total || result.data.list.length
        } else {
          configList.value = []
          pagination.total = 0
        }
      } else {
        message.error(result.message || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 创建配置分组
   */
  const createGroup = async () => {
    submitLoading.value = true
    try {
      // 使用CreateConfigGroup类型，不传递id字段
      const createData: CreateConfigGroup = {
        name: groupFormData.name,
        code: groupFormData.code,
        icon: groupFormData.icon,
        sort: groupFormData.sort,
        remark: groupFormData.remark
      }
      
      const result = await settingApi.createConfigGroup(createData)
      if (result.success) {
        message.success(t('common.createSuccess'))
        groupModalVisible.value = false
        resetGroupForm()
        fetchGroupList()
      } else {
        message.error(result.message || t('common.createFailed'))
      }
    } catch (error) {
      message.error(t('common.createFailed'))
    } finally {
      submitLoading.value = false
    }
  }
  
  /**
   * 更新配置分组
   */
  const updateGroup = async () => {
    submitLoading.value = true
    try {
      // 使用UpdateConfigGroup类型，只传递需要更新的字段
      const updateData: UpdateConfigGroup = {
        name: groupFormData.name,
        code: groupFormData.code,
        icon: groupFormData.icon,
        sort: groupFormData.sort,
        remark: groupFormData.remark
      }
      
      const result = await settingApi.updateConfigGroup(groupFormData.id || '', updateData)
      if (result.success) {
        message.success(t('common.updateSuccess'))
        groupModalVisible.value = false
        resetGroupForm()
        fetchGroupList()
      } else {
        message.error(result.message || t('common.updateFailed'))
      }
    } catch (error) {
      message.error(t('common.updateFailed'))
    } finally {
      submitLoading.value = false
    }
  }
  
  /**
   * 删除配置分组
   */
  const deleteGroup = async (id: string) => {
    try {
      const result = await settingApi.deleteConfigGroup(id)
      if (result.success) {
        message.success(t('common.deleteSuccess'))
        if (currentGroupId.value === id) {
          currentGroupId.value = ''
        }
        fetchGroupList()
      } else {
        message.error(result.message || t('common.deleteFailed'))
      }
    } catch (error) {
      message.error(t('common.deleteFailed'))
    }
  }
  
  /**
   * 创建配置
   */
  const createConfig = async () => {
    submitLoading.value = true
    try {
      // 使用CreateConfig类型，不传递id字段
      const createData: CreateConfig = {
        groupId: configFormData.groupId,
        configName: configFormData.configName,
        configKey: configFormData.configKey,
        configValue: configFormData.configValue,
        valueType: configFormData.valueType,
        builtIn: configFormData.builtIn,
        remark: configFormData.remark
      }
      
      const result = await settingApi.createConfig(createData)
      if (result.success) {
        message.success(t('common.createSuccess'))
        configModalVisible.value = false
        resetConfigForm()
        fetchConfigList()
      } else {
        message.error(result.message || t('common.createFailed'))
      }
    } catch (error) {
      message.error(t('common.createFailed'))
    } finally {
      submitLoading.value = false
    }
  }
  
  /**
   * 更新配置
   */
  const updateConfig = async () => {
    submitLoading.value = true
    try {
      // 使用UpdateConfig类型，只传递需要更新的字段
      const updateData: UpdateConfig = {
        groupId: configFormData.groupId,
        configName: configFormData.configName,
        configValue: configFormData.configValue,
        valueType: configFormData.valueType,
        builtIn: configFormData.builtIn,
        remark: configFormData.remark
      }
      
      const result = await settingApi.updateConfig(configFormData.id || '', updateData)
      if (result.success) {
        message.success(t('common.updateSuccess'))
        configModalVisible.value = false
        resetConfigForm()
        fetchConfigList()
      } else {
        message.error(result.message || t('common.updateFailed'))
      }
    } catch (error) {
      message.error(t('common.updateFailed'))
    } finally {
      submitLoading.value = false
    }
  }
  
  /**
   * 删除配置
   */
  const deleteConfig = async (id: string) => {
    try {
      const result = await settingApi.deleteConfig(id)
      if (result.success) {
        message.success(t('common.deleteSuccess'))
        fetchConfigList()
      } else {
        message.error(result.message || t('common.deleteFailed'))
      }
    } catch (error) {
      message.error(t('common.deleteFailed'))
    }
  }
  
  /**
   * 处理分页变化
   * @param page 页码
   * @param pageSize 每页条数
   */
  const handlePageChange = (page: number, pageSize?: number) => {
    pagination.current = page
    if (pageSize) {
      pagination.pageSize = pageSize
    }
    // 重新获取数据
    fetchConfigList()
  }
  
  // ------------ 辅助方法 ------------
  /**
   * 重置分组表单
   */
  const resetGroupForm = () => {
    Object.assign(groupFormData, {
      name: '',
      code: '',
      icon: 'setting',
      sort: 0,
      remark: ''
    })
    groupFormMode.value = 'add'
  }
  
  /**
   * 重置配置表单
   */
  const resetConfigForm = () => {
    Object.assign(configFormData, {
      groupId: '',
      configName: '',
      configKey: '',
      configValue: '',
      valueType: 'string',
      builtIn: false,
      remark: ''
    })
    configFormMode.value = 'add'
  }
  
  return {
    // 状态
    loading,
    submitLoading,
    groupList,
    configList,
    queryParams,
    pagination,
    groupModalVisible,
    configModalVisible,
    groupFormMode,
    configFormMode,
    currentGroupId,
    groupFormData,
    configFormData,
    groupModalTitle,
    configModalTitle,
    currentGroupName,
    
    // 方法
    fetchGroupList,
    fetchConfigList,
    createGroup,
    updateGroup,
    deleteGroup,
    createConfig,
    updateConfig,
    deleteConfig,
    resetGroupForm,
    resetConfigForm,
    handlePageChange
  }
}) 